package com.xhxi.photobooker.controller;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.xhxi.photobooker.result.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {
    private static final String SECRET_ID = "AKID7E8oKcgXDgx0pTu76uWv5Z2JMCwUpxra";
    private static final String SECRET_KEY = "b1INFwQgjY9XkmHfrtiJitt32oMjtrbA";
    private static final String REGION = "ap-guangzhou";
    private static final String BUCKET = "photobooker-1313102195";

    //采用cos存储
    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file) throws IOException {
        COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
        ClientConfig clientConfig = new ClientConfig(new Region(REGION));
        COSClient cosClient = new COSClient(cred, clientConfig);

        String filename = "avatar/" + UUID.randomUUID() + "_" + file.getOriginalFilename();
        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET, filename, file.getInputStream(), new ObjectMetadata());
        cosClient.putObject(putObjectRequest);

        String url = "https://" + BUCKET + ".cos." + REGION + ".myqcloud.com/" + filename;
        cosClient.shutdown();
        return Result.success(url);
    }
} 